﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using static Ekton_Manage_DTO.EnumClass;

namespace Ekton_Manage_Framework.Methods
{
    public static class LinqHelper
    {
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }

        public static Func<T, Tkey> DynamicLambda<T, Tkey>(string propertyName)
        {
            ParameterExpression p = Expression.Parameter(typeof(T), "p");
            Expression body = Expression.Property(p, typeof(T).GetProperty(propertyName));
            var lambda = Expression.Lambda<Func<T, Tkey>>(body, p);
            return lambda.Compile();
        }
        public static List<T> DynamicLambda<T, Tkey>(this List<T> dynamicList, string propertyName, sortType sort)
        {
            ParameterExpression p = Expression.Parameter(typeof(T), "p");
            Expression body = Expression.Property(p, typeof(T).GetProperty(propertyName));
            var lambda = Expression.Lambda<Func<T, Tkey>>(body, p);
            var compileExpression = lambda.Compile();
            if (sort == sortType.asc)
                return dynamicList.OrderBy(compileExpression).ToList();
            return dynamicList.OrderByDescending(compileExpression).ToList();
        }
    }
}
